package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.AnalysisVisualCatalogDTO;
import com.hunttown.mes.rpc.domain.enums.catalog.CatalogTypeEnum;
import com.hunttown.mes.rpc.domain.query.AnalysisVisualCatalogDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.manage.service.AnalysisCatalogManageService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.manage.service.TransportOperateLogManageService;
import org.apache.velocity.VelocityContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 新闻分类
 * @author: wangjunfu
 * @date: 2018-10-26 15:14:28
 * @description:
 */
@Controller
@RequestMapping(value = "/basic/newscate")
public class NewsCateController {

    private final static Logger logger = LoggerFactory.getLogger(NewsCateController.class);

    private final AnalysisManageManageService manageService;
    private final AnalysisCatalogManageService catalogService;
    private final TransportOperateLogManageService logService;

    @Autowired
    public NewsCateController(AnalysisManageManageService manageService, AnalysisCatalogManageService catalogService, TransportOperateLogManageService logService){
        this.manageService = manageService;
        this.catalogService = catalogService;
        this.logService = logService;
    }

    //region 首页
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, AnalysisVisualCatalogDTOQuery dtoQuery, Integer hideManae) {
        //隐藏管理项：0默认，显示；1隐藏
        hideManae = hideManae == null ? 0 : hideManae;
        model.addAttribute("hideManae", hideManae);

        // 逻辑
        // 1、取当前model_type下的一级分类10条(parent_id = 0)；（但是车辆车型除外，&& dtoQuery.getModelType() != 23 为什么？不解，先取消）
        // 2、然后依次取每条记录下面的子类，组成列表返回结果。
        if (StringUtils.isBlank(dtoQuery.getLikeName())) {
            dtoQuery.setParentId(0);   //非搜索情况下起作用
        }

        dtoQuery.setOrderBy("order by sort desc, id asc");
        Page<AnalysisVisualCatalogDTO> dataPage = catalogService.getForPage(dtoQuery);

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));

        // 依次取出每条记录的子分类
        // 这样处理的好处是：可以把每一个分类下的子分类全部取出来
        List<AnalysisVisualCatalogDTO> catlogList = catalogService.getChildrenForEach(dataPage.getItems(), "|");
        model.addAttribute("catlogList", catlogList);

        // 显示标题
        model.addAttribute("title", CatalogTypeEnum.getEnumByKey(dtoQuery.getModelType()));
        model.addAttribute("dtoQuery", dtoQuery);

        //region 页面按钮权限
        String pin = AdminBaseClass.getPin(request);
        String[] menus = {"G-G-LBSC"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        return "basic/newscate/index";
    }
    //endregion

    //region 编辑&保存
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id, Integer modelType, Integer hideManae) {
        id = id == null ? 0 : id;

        //隐藏管理项：0默认，显示；1隐藏
        hideManae = hideManae == null ? 0 : hideManae;
        model.addAttribute("hideManae", hideManae);

        AnalysisVisualCatalogDTO obj = new AnalysisVisualCatalogDTO();
        obj.setId(id);
        obj.setSort(0);

        if (id > 0) {
            obj = catalogService.getById(id);
        }

        //region 获取上级目录列表
        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();

        //如果是“车辆车型”，那么上级分类应该“车辆品牌”（不这么搞了，各是各的吧，否则容易乱）
        //if (modelType == 23) {
        //    query.setModelType(5);
        //} else {
        //    query.setModelType(modelType);
        //}

        query.setModelType(modelType);
        query.setStopFlag(0);
        query.setPageSize(1000);
        Page<AnalysisVisualCatalogDTO> list = catalogService.getForPage(query);

        if (list != null) {
            //上面限制获取1000条记录，因此要使用这种递归方式
            model.addAttribute("childCateList", catalogService.getListByRecursion(list.getItems(), 0, "|"));
        }
        //endregion

        model.addAttribute("cateObj", obj);
        model.addAttribute("modelType", modelType);

        //region 显示标题
        String title = CatalogTypeEnum.getEnumByKey(modelType);
        if (modelType == 3 || modelType == 7 || modelType == 14) {
            title += "名称";
        }
        model.addAttribute("title", title);
        //endregion

        return "basic/newscate/edit";
    }

    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, AnalysisVisualCatalogDTO objDTO) {

        //结果返回，结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();
        try {
            if (objDTO.getIsWeb() == null) {
                objDTO.setIsWeb(0);
            }
            if (objDTO.getIsWebCate() == null) {
                objDTO.setIsWebCate(0);
            }
            if (objDTO.getIsUploadPic() == null) {
                objDTO.setIsUploadPic(0);
            }
            if (objDTO.getIsSystem() == null) {
                objDTO.setIsSystem(0);
            }
            if (objDTO.getStopFlag() == null) {
                objDTO.setStopFlag(0);
            }

            //新增时检验是否唯一
            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
                query.setCatalogNameEn(objDTO.getCatalogNameEn());
                query.setDeleteFlag(0);
                AnalysisVisualCatalogDTO obj = catalogService.getByQuery(query);
                if (obj != null && obj.getId() > 0) {
                    //说明已经有此记录了，不能插入。
                    map = OperateCode.CompositionResult(map, -10, "此英文名称已存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setDeleteFlag(0);

                objDTO = catalogService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            } else {
                //更新
                //将不需要更新的字段设置为NULL
                if (objDTO.getModelType() != 16) {  //购方税号可以修改
                    objDTO.setCatalogNameEn(null);
                }

                Boolean isNext = catalogService.updateInfoById(objDTO);
                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 28, objDTO.getId(), 2,
                    "更新全站分类信息",
                    FastJsonUtils.toJSONString(objDTO),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;
        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(HttpServletRequest request, Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = catalogService.delete(id);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 28, id, 4,
                    "删除全站分类信息",
                    "记录删除：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    //endregion

    //region 启停用
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(HttpServletRequest request, Integer id, Integer status) {
        //结果返回，结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = catalogService.changeState(id, status);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 28, id, 4,
                    "删除全站分类信息",
                    "记录删除：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    //endregion

    //region 根据 modelType 获取分类子列表

    /**
     * 根据 modelType 获取分类子列表
     *
     * @param modelType
     * @return
     */
    @RequestMapping(value = "/getChildCateList", method = RequestMethod.POST)
    @ResponseBody
    public String getChildList(int modelType) {
        //结果返回，结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            // 获取column 列表
            if (modelType > 0) {
                AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
                query.setModelType(modelType);
                query.setStopFlag(0);
                query.setPageSize(1000);
                Page<AnalysisVisualCatalogDTO> columnList = catalogService.getForPage(query);
                if (columnList != null) {
                    String templateFile = "velocity/template/catalog-list.vm";
                    VelocityContext context = new VelocityContext();
                    context.put("childCateList", catalogService.getListByRecursion(columnList.getItems(), 0, "|"));
                    String html = VelocityUtils.getTemplateContent(templateFile, context);

                    map.put("selectHtml", html);
                }
            }

            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map.put("returnResult", "");
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    //endregion

    //region 获取当前单位的下级及下下...级部门

    /**
     * 获取当前分类的下级及下下...级分类
     *
     * @param cateId    分类ID
     * @param modelType 分类类型
     * @return
     */
    @RequestMapping(value = "/getSubCatalog", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getSubCatalog(Integer cateId, Integer modelType) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (cateId == null) {
            cateId = 0;
        }

        if (cateId > 0) {
            AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
            query.setParentId(cateId);
            if (modelType != null && modelType > 0) {
                query.setModelType(modelType);
            }
            query.setStopFlag(0);
            query.setPageSize(1000);
            Page<AnalysisVisualCatalogDTO> catalogPage = catalogService.getForPage(query);

            if (catalogPage != null) {
                map.put("catalogList", catalogService.getChildrenForEach(catalogPage.getItems(), "|"));
            }

            map.put("returnCode", 1);
        }

        return map;
    }

    //endregion

    //region 获取查询列表

    /**
     * 获取查询列表
     *
     * @param model
     * @param name      关键词
     * @param modeltype 类型
     * @return
     */
    @RequestMapping(value = "/selectProjects", method = RequestMethod.POST)
    public String selectProjects(Model model, String name, Integer modeltype) {

        if (StringUtils.isBlank(name) || modeltype == null || modeltype <= 0) {
            return "garage/repair-order/projects-select-model";
        }

        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
        query.setLikeName(name.trim());
        query.setModelType(modeltype);
        query.setPageSize(20);
        query.setStopFlag(0);
        Page<AnalysisVisualCatalogDTO> choicePage = catalogService.getForPage(query);
        model.addAttribute("page", choicePage);

        return "garage/repair-order/projects-select-model";
    }
    //endregion

    //region 获取查询列表（带分页）

    /**
     * 获取查询列表（带分页）
     *
     * @param name      关键词
     * @param modeltype 类型，见枚举
     * @param from      0默认
     * @param pn        页码
     * @param pageSize  分页大小
     * @return map
     */
    @RequestMapping(value = "/selectProjectPage", method = RequestMethod.POST)
    @ResponseBody
    public Map<Object, Object> selectProjectPage(String name, Integer modeltype, Integer from, Integer pn, Integer pageSize) {
        pn = (pn == null || pn <= 0) ? 1 : pn;
        pageSize = (pageSize == null || pageSize <= 0) ? 5 : pageSize;

        Map<Object, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("pn", pn);
        map.put("pageSize", pageSize);

        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
        if (StringUtils.isNotBlank(name)) {
            query.setLikeName(name.trim());
        }
        query.setModelType(modeltype);
        query.setPn(pn);
        query.setPageSize(pageSize);
        query.setStopFlag(0);
        query.setOrderBy("order by id desc");
        Page<AnalysisVisualCatalogDTO> dataPage = catalogService.getForPage(query);

        map.put("projectAjaxPage", dataPage);
        map.put("projectAjaxPagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));

        return map;
    }
    //endregion

    //region 获取查询信息
    @RequestMapping(value = "/getProjectInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getProjectInfo(Integer proId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (proId == null || proId <= 0) {
            return map;
        }

        AnalysisVisualCatalogDTO dto = catalogService.getFromCacheId(proId);
        if (dto != null) {
            map.put("name", dto.getCatalogName());
            map.put("returnCode", 1);
        }

        return map;
    }
    //endregion

    //region 一键生成菜单通用分类ID配置

    @RequestMapping(value = "/oneKeyCreateMenuCatalog", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> oneKeyCreateMenuCatalog() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        //格式：{"W-G-JSB": 634, "W-G-HYJY": 633, "W-J-SYHD": 624, "W-J-GSJJ": 657, "W-J-QYWH": 656, "W-J-GSRY": 631, "W-J-HZHB": 622, "W-J-LXWM": 623, "W-G-CPZS": 618, "W-G-GSFW": 619, "W-G-GSHD": 620, "W-G-KHAL": 621, "W-X-XYXW": 610, "T-T-GSTZ": 599}
        Map<String, Integer> menumap = new HashMap<>();

        //要拷贝的企业ID
        int copyEntId = 1;

        //公司信息
        int createid = createMenuCatalog("gongsixinxi", copyEntId, 0);

        if (createid > 0) {
            //|--公司通知
            createid = createMenuCatalog("tongzhi", copyEntId, createid);
            menumap.put("T-T-GSTZ", createid);

            //|--会议纪要
            createid = createMenuCatalog("huiyijiyao", copyEntId, createid);
            menumap.put("W-G-HYJY", createid);
        }

        //关于我们
        createid = createMenuCatalog("guanyuwomen", copyEntId, 0);

        if (createid > 0) {
            //|--公司荣誉
            createid = createMenuCatalog("gongsirongyu", copyEntId, createid);
            menumap.put("W-J-GSRY", createid);

            //|--企业文化
            createid = createMenuCatalog("qiyewenhua", copyEntId, createid);
            menumap.put("W-J-QYWH", createid);

            //|--公司简介
            createid = createMenuCatalog("gongsijianjie", copyEntId, createid);
            menumap.put("W-J-GSJJ", createid);
        }

        //联系我们
        createid = createMenuCatalog("lianxiwomen", copyEntId, 0);
        menumap.put("W-J-LXWM", createid);

        //公司活动
        createid = createMenuCatalog("gongsihuodong", copyEntId, 0);
        menumap.put("W-G-GSHD", createid);

        //行业新闻
        createid = createMenuCatalog("shehuixinwen", copyEntId, 0);
        menumap.put("W-X-XYXW", createid);

        //客户案例
        createid = createMenuCatalog("kehuanli", copyEntId, 0);
        menumap.put("W-G-KHAL", createid);

        //合作伙伴
        createid = createMenuCatalog("hezuohuoban", copyEntId, 0);
        menumap.put("W-J-HZHB", createid);

        //首页幻灯
        createid = createMenuCatalog("shouyehuandeng", copyEntId, 0);
        menumap.put("W-J-SYHD", createid);

        //公司服务
        createid = createMenuCatalog("gongsifuwu", copyEntId, 0);
        menumap.put("W-G-GSFW", createid);

        //产品展示
        createid = createMenuCatalog("chanpinzhanshi", copyEntId, 0);
        menumap.put("W-G-CPZS", createid);

        //记事本
        createid = createMenuCatalog("jishiben", copyEntId, 0);
        menumap.put("W-G-JSB", createid);

        map.put("jsonData", FastJsonUtils.toJSONString(menumap));
        map.put("returnCode", 1);
        map.put("returnMessage", "通用菜单生成成功！");
        return map;
    }

    //生成
    private Integer createMenuCatalog(String key, Integer copyEntid, Integer parentId) {
        AnalysisVisualCatalogDTO dto = catalogService.getByCateEnName(key);
        if (dto != null) {
            return dto.getId();
        }

        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
        query.setEntId(copyEntid);
        query.setCatalogNameEn(key);
        query.setStopFlag(0);
        AnalysisVisualCatalogDTO orignDTO = catalogService.getByQuery(query);
        if (orignDTO == null) {
            return 0;
        }

        orignDTO.setId(0);
        orignDTO.setParentId(parentId);
        orignDTO.setEntId(null);
        orignDTO.setCreateTime(new Date());
        orignDTO = catalogService.insert(orignDTO);
        return orignDTO.getId();
    }
    //endregion
}